<template>
  <el-menu :default-active="activeIndex" :mode="menuMode" :default-openeds="openeds"
    @select="handleSelect">
    <!-- 自定义选中样式 -->
    <!-- :background-color="menuStyle.backGroundColor"
    :text-color="menuStyle.textColor"
    :active-text-color="menuStyle.activeColor" -->
    <template v-for="item in menus" :key="item.path">
      <el-menu-item v-if="!item.children" :index="item.path" :route="item.path" @click="handleClick">
        {{ item.label }}
      </el-menu-item>
      <SubMenuItem v-else :menu="item" @check="handleClick" />
    </template>
  </el-menu>
</template>
<script lang="ts" setup>
  import { ref, toRefs, PropType, watch, nextTick } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { MenuItem } from '@/router/menu';
  import SubMenuItem from './SubMenuItem.vue';

  interface menuStyleProps {
    backGroundColor: string;
    textColor: string;
    activeColor: string;
  }

  const route = useRoute();
  const router = useRouter()
  const activeIndex = ref(route.path);
  const isShow = ref(true)

  watch(route, ({ path }) => activeIndex.value = path)

  const lastRoute = ref(route.path)
  const handleClick = (item: any) => {
    const path = item.index

    if (path.startsWith('http')) {
      window.open(path)
      isShow.value = false
      nextTick(() => {
        router.replace({ path: lastRoute.value })
        activeIndex.value = path
        isShow.value = true
      })
    } else {
      lastRoute.value = path
      router.push({ path: path })
    }
  }

  const handleSelect = (key: string) => {
    if (key !== route.path) {
      activeIndex.value = route.path
    } else {
      activeIndex.value = key
    }
  };

  const props = defineProps({
    menuMode: {
      type: String,
      default: 'vertical',
    },
    menuStyle: {
      type: Object as PropType<menuStyleProps>,
      default: (): menuStyleProps => ({ backGroundColor: '#333', textColor: '#fff', activeColor: '#ffd04b' }),
    },
    menus: {
      type: Array as PropType<MenuItem[]>,
      default: () => [],
    },
  });

  const { menuMode, menuStyle, menus } = toRefs(props);

  const openeds = ref(['example'])

</script>

<style lang="scss" scoped>
  .el-menu {
    border-right: none;
    flex-grow: 1;
  }
</style>
